<template>
  <div class="tabnav">
    <el-tabs
      v-model="editableTabsValue"
      type="card"
      @tab-remove="removeTab"
      @tab-click="goto"
    >
      <el-tab-pane
        class="tab"
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :closable="editableTabs.length > 1 ? true : false"
      >
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: "Tabnav",
  data() {
    return {};
  },
  computed: {
    tabIndex() {
      return this.$store.state.tabIndex;
    },
    editableTabs: {
      get() {
        return this.$store.state.editableTabs;
      },
      set(val) {
        this.$store.state.editableTabs = val;
      },
    },
    editableTabsValue: {
      get() {
        return this.$store.state.editableTabsValue;
      },
      set(val) {
        this.$store.state.editableTabsValue = val;
      },
    },
  },
  methods: {
    // addTab() {
    //   this.$store.commit("addTab");
    // },
    // removeTab(targetName) {
    //   this.$store.commit("removeTab"); 
    // },
    removeTab(targetName) {
      if (targetName == 0) return;
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
    },
    goto(a) {
      if (a.index == 0) {
        if (location.hash.split("/")[1] !== "index")
          this.$router.push({ name: "index" });
        return;
      }
      let activeName = this.editableTabsValue;
      console.log(a.index, activeName);

      this.editableTabs.forEach((item, index) => {
        if (index == a.index) {
          let name = this.editableTabs[index].path;
          // if (location.hash.split("/")[2] !== name) this.$router.push({ name });
          this.$router.push(name);
          return;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.tabnav{
  margin:0 10px;
}
</style>
